package com.phone.servlet;

import com.phone.DBHelper;
import com.phone.ParameterCheck;
import com.phone.entity.Result;
import com.phone.entity.Results;
import com.phone.entity.ServiceControl;
import com.phone.exception.BaseException;
import com.phone.handle.ControlHandle;
import com.phone.handle.ServiceHandle;
import com.phone.json.JsonControl;
import com.phone.json.JsonService;
import com.phone.utils.TextUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.invoke.SwitchPoint;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by tisen on 2017/8/22.
 */
@WebServlet(name = "Control", urlPatterns = "/control")
public class ControlService extends BaseServlet {

    private static final String ACTION_SET = "set";
    private static final String ACTION_SEARCH = "search";

    private static final String ACTION_PARAMETER = "action";

    private static final String MODEL_PARAMETER = "model";
    private static final String STATUS_PARAMETER = "status";
    private static final String TIME_PARAMETER = "time";
    private static final long DEFAULT_MILLIS = 0;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ParameterCheck check = new ParameterCheck(request);
        Session session = DBHelper.getSession();
        session.beginTransaction();
        JSONObject object = new JSONObject();
        try {
            String action = check.getParameterString(ACTION_PARAMETER, true);
            switch (action) {
                case ACTION_SET:
                    object = set(check, session);
                    break;
                case ACTION_SEARCH:
                    object = search(check, session);
                    break;
                default:
                    break;
            }
            session.getTransaction().commit();
        } catch (HibernateException exception) {
            exception.printStackTrace();
            session.getTransaction().rollback();
        } catch (BaseException exception) {
            exception.printStackTrace();
            session.getTransaction().rollback();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen())
                session.close();
            out(response, object.toString());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    private JSONObject set(ParameterCheck check, Session session) throws Exception {
        String model = check.getParameterString(MODEL_PARAMETER, false);
        boolean status = check.getParameterBoolean(STATUS_PARAMETER, true, false);
        System.out.println("model = " + model + " | status = " + status);

        session.saveOrUpdate(new ServiceControl(model, status));
        return new JSONObject(new Result<String>(SUCCESS, "set status success", model));
    }

    private JSONObject search(ParameterCheck check, Session session) throws Exception {
        long time = check.getParameterLong(TIME_PARAMETER, true, DEFAULT_MILLIS);
        System.out.println(time);
        List<JsonControl> jsonControls = new ArrayList<>();
        String hql;
        if (time == 0) {
            hql = "select control.model,count(*),control.status from ServiceRecord record left join record.model control group by record.model";
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dataString = "'" + simpleDateFormat.format(new Date(System.currentTimeMillis() - time)) + "'";
            String dateNow = "'" + simpleDateFormat.format(new Date()) + "'";
            hql = "select control.model,count(*),control.status from ServiceRecord record left join record.model control where record.date between " + dataString + " and " + dateNow + " group by record.model";
            System.out.println(hql);
        }
        Query query = DBHelper.getSession().createQuery(hql);
        List list = query.list();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Object[] result = (Object[]) it.next();
            jsonControls.add(new JsonControl((String) result[0], Integer.parseInt(result[1].toString()), Boolean.parseBoolean(result[2].toString())));
        }
        return new JSONObject(new Results<JsonControl>(SUCCESS, "search success", jsonControls.size(), 0, 0, jsonControls));
    }

}
